package com.flink.java.demo.transform;

import com.flink.java.demo.FlinkConstant;
import com.flink.java.demo.bean.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 *
 * 滚动聚合算子
 *
 */
public class TransformTest2_RollingAggregation {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 从文件读取数据
        DataStream<String> inputStream = env.readTextFile(FlinkConstant.sensorPath);

        // 转换成SensorReading类型
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        } );

        /**
         * 根据字段名称分组
         * KeyedStream<SensorReading, Tuple> keyedStream = dataStream.keyBy("id"); //过时了
         */
        KeyedStream<SensorReading, String> keyedStream = dataStream.keyBy(data -> data.getId());
        //KeyedStream<SensorReading, String> keyedStream = dataStream.keyBy(SensorReading::getId);
        keyedStream.print("groupResult");

        // 滚动聚合，取当前最大的温度值
        DataStream<SensorReading> resultStream = keyedStream.maxBy("temperature");

        /*
        DataStream<Long> dataStream1 = env.fromElements(1L, 34L, 4L, 657L, 23L);
        KeyedStream<Long, Integer> keyedStream2 = dataStream1.keyBy(new KeySelector<Long, Integer>() {
            @Override
            public Integer getKey(Long value) throws Exception {
                return value.intValue() % 2;
            }
        });
                keyedStream1.print("key1");
        keyedStream2.sum(0).print("key2");

*/


        resultStream.print("result");
        env.execute();
    }
}
